package com.xy.blog.article.domain.service.oss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

/**
 * @author zanhonglei
 * @version V1.0
 * @Description:
 * @date 2020/6/7
 */
@Component
public class OSSServices {


    @Value("${endpoint}")
    private String endpoint;

    @Value("${accessKeyId}")
    private String accessKeyId;

    @Value("${accessKeySecret}")
    private String accessKeySecret;

    @Value("${bucketName}")
    private String bucketName;

    /**
     * 保存文件到oss
     * @param bytes
     * @param fileName
     */
    public void saveFile(byte[] bytes,String fileName) throws Exception{
        /*
         * Constructs a client instance with your account for accessing OSS
         */
        OSS client = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 上传内容到指定的存储空间（bucketName）并保存为指定的文件名称（objectName）。
            client.putObject(bucketName, fileName, new ByteArrayInputStream(bytes));

            OSSObject object = client.getObject(bucketName, fileName);
            InputStream objectContent = object.getObjectContent();
            objectContent.close();
        } finally {
            /*
             * Do not forget to shut down the client finally to release all allocated resources.
             */
            client.shutdown();
        }
    }

    /**
     * 获取url
     * @param objectName
     * @returns
     */
    public String getUrl(String objectName,String ...param) {
//        return  "https://" + bucketName + "." + endpoint + "/" + objectName + "?x-oss-process=image/resize,w_500";
        StringBuilder template = new StringBuilder("https://" + bucketName + "." + endpoint + "/" + objectName);
        if (param != null) {
            for (String item : param) {
                template.append(item);
            }
        }
        return template.toString();
    }

}
